﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Volo.Abp;

namespace Xms.Abp.Core;

public class DynamicConditionModel
{
    public int Index { get; set; }
    public DynamicConditionType Type { get; set; }
    public DynamicConditinRelation Relation { get; set; }
    public DynamicConditionValue Condition { get; set; }
    public List<DynamicConditionModel> Group { get; set; }
    public Expression<Func<T, bool>> Build<T>()
    {
        if (Type == DynamicConditionType.Condition)
        {
            if(Condition == null)
            {
                throw new UserFriendlyException("无法构建表达式树");
            }
            return Condition.Build<T>();
        }
        else
        {
            if (Group == null || Group.Count == 0)
            {
                throw new UserFriendlyException("无法构建表达式树");
            }
            var v = Relation == DynamicConditinRelation.And;
            Expression<Func<T, bool>> where = r => v;
            Group.ForEach(r =>
            {
                var expression = r.Build<T>();
                if (v)
                {
                    where = where.And(expression);
                }
                else
                {
                    where = where.Or(expression);
                }
            });
            return where;
        }
    }
}
